package com.awcall.iot.controller;


import com.awcall.iot.common.BaseController;
import com.awcall.iot.common.ResponseResult;
import com.awcall.iot.model.Project;
import com.awcall.iot.model.Role;
import com.awcall.iot.model.SystemUser;
import com.awcall.iot.model.UserProject;
import com.awcall.iot.service.*;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 管理员表 前端控制器
 * </p>
 *
 * @author wuhui
 * @since 2018-03-05
 */
@RestController
@RequestMapping("/admin/systemUser")
public class SystemUserController extends BaseController {

    @Autowired
    private ISystemUserService iSystemUserService;
    @Autowired
    private IRoleService roleService;
    @Autowired
    private ISettingService iSettingService;
    @Autowired
    private IProjectService iProjectService;
    @Autowired
    private IUserProjectService iUserProjectService;

    @GetMapping("/index")
    public ResponseResult index(String username, Page<SystemUser> page) {
        Wrapper<SystemUser> wrapper = new EntityWrapper<SystemUser>()
                .like(SystemUser.USERNAME, username)
                .orderBy(SystemUser.ID, false);
        Page<SystemUser> userPage = iSystemUserService.selectPage(page, wrapper);
        for (SystemUser systemUser : userPage.getRecords()) {
            EntityWrapper<Role> entityWrapper = new EntityWrapper<>();
            entityWrapper.eq(Role.ID, systemUser.getRoleId());
            Role role = roleService.selectOne(entityWrapper);
            systemUser.setRoleName(role.getRoleName());

            EntityWrapper<UserProject> userProjectEntityWrapper = new EntityWrapper<>();
            userProjectEntityWrapper.eq(UserProject.USER_ID,systemUser.getId()).setSqlSelect(UserProject.PROJECT_ID);
            List<Object> objects = iUserProjectService.selectObjs(userProjectEntityWrapper);
            if (null != objects && objects.size() != 0){
                StringBuffer stringBuffer = new StringBuffer();
                for (Object o : objects){
                    Integer i = (Integer) o;
                    Project project = iProjectService.selectById(i);
                    stringBuffer.append(project.getName()).append(" ");
                }
                systemUser.setProjectNames(stringBuffer.toString());
            }
        }
        return new ResponseResult<>(userPage);
    }

    @GetMapping("/list")
    public ResponseResult list(){

        List<SystemUser> systemUsers = iSystemUserService.selectList(null);

        return new ResponseResult<>(systemUsers);
    }

    /**
     * 查询用户
     *
     * @param username
     * @return
     */
    @GetMapping("/search")
    public ResponseResult search(String username) {
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(username.trim())) {
            return new ResponseResult<>(new ArrayList<>());
        }

        Wrapper<SystemUser> wrapper = new EntityWrapper<SystemUser>()
                .like(SystemUser.USERNAME, username)
                .orderBy(SystemUser.ID, false).last("limit 100");

        List<SystemUser> systemUsers = iSystemUserService.selectList(wrapper);
        return new ResponseResult<>(systemUsers);
    }

    @GetMapping("/detail")
    public ResponseResult detail(Integer id) {
        SystemUser user = iSystemUserService.selectById(id);
        String company = iSettingService.getValue("COMPANY");

        user.setCompanyName(company);
        return new ResponseResult<>(user);
    }

    @PostMapping("/insert")
    public ResponseResult insert(@RequestBody SystemUser systemUser) {
        Wrapper<SystemUser> ew = new EntityWrapper<SystemUser>()
                .eq("username", systemUser.getUsername())
                .last("limit 1");
        SystemUser user = iSystemUserService.selectOne(ew);
        if (null == user) {
            systemUser.setPassword(DigestUtils.md5Hex(systemUser.getPassword()));
            systemUser.setStatus(0);
            if (null != systemUser.getProjectId() && 0 != systemUser.getProjectId()){
                Project project = iProjectService.selectById(systemUser.getProjectId());
                systemUser.setProjectId(project.getProjectId());
                systemUser.setProjectName(project.getName());
            }
            iSystemUserService.insert(systemUser);
            return new ResponseResult();
        } else {
            return new ResponseResult<>(1, "账号已注册");
        }

    }

    @PostMapping("/update")
    public ResponseResult update(@RequestBody SystemUser systemUser) {
        if (StringUtils.isNotEmpty(systemUser.getPassword())) {
            systemUser.setPassword(DigestUtils.md5Hex(systemUser.getPassword()));
        }

        SystemUser systemUser1 = iSystemUserService.selectById(systemUser.getId());
        if (StringUtils.isEmpty(systemUser.getPassword())){
            systemUser.setPassword(systemUser1.getPassword());
        }

        if (null == systemUser.getProjectId()){
            systemUser.setProjectId(0);
            systemUser.setProjectName("");
        }

        if (null != systemUser.getProjectId() && 0 != systemUser.getProjectId()){
            Project project = iProjectService.selectById(systemUser.getProjectId());
            systemUser.setProjectId(project.getProjectId());
            systemUser.setProjectName(project.getName());
        }

        iSystemUserService.updateById(systemUser);
        return new ResponseResult();
    }

    @PostMapping("/updatep")
    public ResponseResult updatep(@RequestBody SystemUser systemUser) {
        if (StringUtils.isNotEmpty(systemUser.getPassword())) {
            systemUser.setPassword(DigestUtils.md5Hex(systemUser.getPassword()));
        }

        EntityWrapper<SystemUser> entityWrapper = new EntityWrapper<>();
        entityWrapper.eq("telephone",systemUser.getTelephone());
        SystemUser systemUser1 = iSystemUserService.selectOne(entityWrapper);

        if (null == systemUser1){
            return new ResponseResult<>(1, "此手机号没有对应的账号");
        }
        systemUser.setId(systemUser1.getId());
        iSystemUserService.updateById(systemUser);
        return new ResponseResult();
    }

    @PostMapping("/updatePassword")
    public ResponseResult updatePassword(@RequestBody SystemUser systemUser) {
        if (StringUtils.isEmpty(systemUser.getOldPassword())) {
            return new ResponseResult(1, "原密码不能为空");
        }
        if (StringUtils.isEmpty(systemUser.getPassword())) {
            return new ResponseResult(2, "新密码不能为空");
        }

        SystemUser systemUser1 = iSystemUserService.selectById(getSystemUserId());
        if (!systemUser1.getPassword().equals(DigestUtils.md5Hex(systemUser.getOldPassword()))) {
            return new ResponseResult(3, "原密码错误");
        }

        systemUser1.setPassword(DigestUtils.md5Hex(systemUser.getPassword()));
        iSystemUserService.updateById(systemUser1);
        return new ResponseResult();
    }

    @PostMapping("/delete")
    public ResponseResult delete(@RequestBody SystemUser systemUser) {
        boolean b = iSystemUserService.deleteById(systemUser);
        if (b) {
            return new ResponseResult();
        } else {
            return new ResponseResult(1, "删除失败");
        }
    }

    @PostMapping("/updateRole")
    public ResponseResult updateRole(@RequestBody SystemUser systemUser) {
        ResponseResult responseResult = iSystemUserService.updateRole(systemUser);
        return new ResponseResult<>(responseResult);
    }

    @GetMapping("/role")
    public ResponseResult role(Long id) {
        ResponseResult responseResult = roleService.findByAdminUserId(id);
        return new ResponseResult<>(responseResult);
    }

    @GetMapping("/show")
    public ResponseResult show(Long id) {
        List<Integer> userProjectList = iSystemUserService.finProjectByUserId(id);
        return new ResponseResult<>(userProjectList);
    }

    @PostMapping("/updateProject")
    public ResponseResult updateProject(@RequestBody SystemUser systemUser) {
        return iSystemUserService.updateProject(systemUser);
    }

}
